package com.llb666.shop.payment.domain.service;

import com.llb666.shop.payment.domain.entity.PreOrderResult;
import com.llb666.common.core.utils.HttpUtil;
import com.llb666.shop.payment.domain.entity.PayResult;
import com.llb666.shop.payment.domain.entity.PreOrder;
import com.llb666.shop.payment.infrastructure.config.WXPayConfig;
import com.llb666.shop.payment.infrastructure.utils.Sign;
import com.llb666.shop.payment.infrastructure.utils.XmlUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;

/**
 * 微信统一下单.
 *
 * @author llb666
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@Slf4j
public class WxOrderService {

    private final WXPayConfig wxPayConfig;

    /**
     * 获取微信支付结果.
     *
     * @param inputStream -
     * @return 微信支付结果
     * @throws Exception 异常
     */
    public PayResult getWxPayResult(InputStream inputStream) throws Exception {
        StringBuilder result = new StringBuilder();
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        PayResult pr = (PayResult) XmlUtil.xml2Object(result.toString(), PayResult.class);
        log.info(pr.toString());
        return pr;
    }

    /**
     * 统一下单.
     *
     * @param body       商品描述
     * @param outTradeNo 商户订单号
     * @param totalFee   订单总金额
     * @return PreOrderResult
     * @throws Exception 异常，主要来源于xml转换.
     */
    public PreOrderResult placeOrder(String body, String outTradeNo, String totalFee) throws Exception {
        // 生成随机字符串
        String nonce_str = UUID.randomUUID().toString().trim().replaceAll("-", "");
        // 获得签名
        String sign = Sign.createSign(wxPayConfig, body, nonce_str, outTradeNo, totalFee);
        // 生成预付单对象
        PreOrder preOrder = PreOrder.createPreOrder(wxPayConfig, body, nonce_str, outTradeNo, totalFee, sign);
        // Object转换为XML
        String xml = XmlUtil.object2Xml(preOrder, PreOrder.class);
        // 统一下单地址
        String url = wxPayConfig.getPlaceOrderUrl();
        // 调用微信统一下单地址
        String returnXml = HttpUtil.sendPost(url, xml);

        // XML转换为Object
        return (PreOrderResult) XmlUtil.xml2Object(returnXml, PreOrderResult.class);
    }
}
